package com.hzlemone.form.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.hzlemone.enums.ResponseStatusEnum;
import com.hzlemone.form.model.request.FormInfoRequestDTO;
import com.hzlemone.form.model.response.FormInfoGetResponseDTO;
import com.hzlemone.form.model.response.FormInfoListResponseDTO;
import com.hzlemone.form.model.search.FormInfoSearchDTO;
import com.hzlemone.form.service.IFormInfoService;
import com.hzlemone.mapper.model.db.FormInfoDO;
import com.hzlemone.response.ResponseDTO;
import com.hzlemone.response.ResponsePageDTO;
import com.hzlemone.utils.CollectionMapperDecorator;
import com.hzlemone.utils.JsonUtil;

/**
 * @ClassName FormInfoController.java
 * @Description 表单信息 REST API
 * @author Francis.LW
 * @date 2017年11月13日
 **/

@RestController
@RequestMapping("/admin/form")
@Api(value = "表单信息  REST API", description = "表单信息  REST API")
public class FormInfoController {

	private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

	@Autowired
	CollectionMapperDecorator collectionMapperDecorator;

	@Autowired
	IFormInfoService formInfoService;

	@ApiOperation(value = "获取表单信息列表", notes = "获取表单信息列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "currentpage", value = "当前页数", defaultValue = "1", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = "pagesize", value = "每页记录数", defaultValue = "10", paramType = "query", required = true, dataType = "int") })
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ResponseDTO listFormInfo(
			@RequestParam(name = "currentpage", defaultValue = "1") int currentPage,
			@RequestParam(name = "pagesize", defaultValue = "10") int pageSize,
			@RequestBody(required = false) FormInfoSearchDTO search) {
		ResponseDTO responseDTO = new ResponseDTO();

		FormInfoDO param = new FormInfoDO();

		// 设置搜索参数
		if (search != null) {
			param = collectionMapperDecorator.map(search, FormInfoDO.class);
		}
		// 设置分页参数
		param.setPage(currentPage);
		param.setRows(pageSize);

		PageInfo<FormInfoDO> formInfoPageInfo = formInfoService
				.listFormInfoByPage(param);

		ResponsePageDTO<FormInfoListResponseDTO> responsePageDTO = new ResponsePageDTO<FormInfoListResponseDTO>();
		List<FormInfoListResponseDTO> formInfoResponseDTOs = new ArrayList<FormInfoListResponseDTO>();
		if (currentPage <= formInfoPageInfo.getPages()) {
			formInfoResponseDTOs = (List<FormInfoListResponseDTO>) collectionMapperDecorator
					.mapCollection(formInfoPageInfo.getList(),
							FormInfoListResponseDTO.class);
		}

		responsePageDTO.setList(formInfoResponseDTOs);
		responsePageDTO.setTotalRecord(formInfoPageInfo.getTotal());

		responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
		responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
		responseDTO.setData(responsePageDTO);

		logger.info("表单信息列表：" + JsonUtil.toJson(responsePageDTO));
		return responseDTO;
	}

	@ApiOperation(value = "添加表单信息信息", notes = "添加表单信息信息")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ResponseDTO addFormInfo(
			@Valid @RequestBody FormInfoRequestDTO formInfoRequestDTO,
			BindingResult errorResult) {
		ResponseDTO responseDTO = new ResponseDTO();

		// 验证表单填写的信息
		List<String> errorTag = formInfoRequestDTO.getFormError(errorResult);
		if (errorTag.size() != 0) {
			responseDTO.setCode(ResponseStatusEnum.FORM_ERROR.getCode());
			responseDTO.setMessage(ResponseStatusEnum.FORM_ERROR.getMessage());
			responseDTO.setData(errorTag);
			return responseDTO;
		}

		try {
			formInfoService.saveFormInfo(formInfoRequestDTO);
			responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
			responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
		} catch (Exception ex) {
			logger.error("表单信息插入信息报错如下：" + ex.toString());
			responseDTO.setCode(ResponseStatusEnum.ERROR.getCode());
			responseDTO.setMessage(ResponseStatusEnum.ERROR.getMessage());
		}

		return responseDTO;
	}

	@ApiOperation(value = "获取表单信息信息", notes = "获取表单信息信息")
	@ApiImplicitParam(name = "id", value = "表单信息id", paramType = "path", required = true, dataType = "String")
	@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
	public ResponseDTO getFormInfoById(@PathVariable("id") String id) {
		ResponseDTO responseDTO = new ResponseDTO();

		FormInfoDO FormInfo = formInfoService.getFormInfoById(id);
		if (FormInfo != null) {
			FormInfoGetResponseDTO formInfoGetResponseDTO = collectionMapperDecorator
					.map(FormInfo, FormInfoGetResponseDTO.class);
			logger.info("表单信息数据：" + JsonUtil.toJson(formInfoGetResponseDTO));
			responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
			responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
			responseDTO.setData(formInfoGetResponseDTO);
		} else {
			responseDTO.setCode(ResponseStatusEnum.NOTFOUNT.getCode());
			responseDTO.setMessage(ResponseStatusEnum.NOTFOUNT.getMessage());
		}
		return responseDTO;
	}

	@ApiOperation(value = "编辑表单信息信息", notes = "编辑表单信息信息")
	@ApiImplicitParam(name = "id", value = "表单信息id", paramType = "path", required = true, dataType = "String")
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public ResponseDTO updateFormInfo(@PathVariable("id") String id,
			@Valid @RequestBody FormInfoRequestDTO formInfoRequestDTO,
			BindingResult errorResult) {
		ResponseDTO responseDTO = new ResponseDTO();

		// 验证表单填写的信息
		List<String> errorTag = formInfoRequestDTO.getFormError(errorResult);
		if (errorTag.size() != 0) {
			responseDTO.setCode(ResponseStatusEnum.FORM_ERROR.getCode());
			responseDTO.setMessage(ResponseStatusEnum.FORM_ERROR.getMessage());
			responseDTO.setData(errorTag);
			return responseDTO;
		}

		try {
			formInfoService.updateFormInfo(id, formInfoRequestDTO);
			responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
			responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
		} catch (Exception ex) {
			logger.error("表单信息编辑报错如下：" + ex.toString());
			responseDTO.setCode(ResponseStatusEnum.ERROR.getCode());
			responseDTO.setMessage(ResponseStatusEnum.ERROR.getMessage());
		}

		return responseDTO;
	}

	@ApiOperation(value = "删除表单信息信息", notes = "删除表单信息信息，可进行单条或批量删除")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public ResponseDTO removeFormInfo(@RequestBody String[] ids) {
		ResponseDTO responseDTO = new ResponseDTO();
		try {
			formInfoService.removeFormInfo(ids);
			responseDTO.setCode(ResponseStatusEnum.SUCCESS.getCode());
			responseDTO.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
		} catch (Exception ex) {
			logger.error("表单信息删除报错如下：" + ex.toString());
			responseDTO.setCode(ResponseStatusEnum.ERROR.getCode());
			responseDTO.setMessage(ResponseStatusEnum.ERROR.getMessage());
		}
		return responseDTO;
	}
}
